import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { 
  generateDeviceId, 
  getDeviceInfo, 
  getLocalDeviceId, 
  saveDeviceId, 
  registerDeviceAndSaveId,
  shouldReRegisterDevice,
  validateDeviceId
} from '../utils/device'
import type { RegisteredDevice, DeviceType } from '../types'

interface DeviceStoreState {
  // 设备信息
  deviceId: string | null;
  deviceName: string;
  deviceType: 'mobile' | 'browser' | 'desktop';
  isRegistered: boolean;
  registrationError: string | null;

  // 设备能力
  capabilities: {
    speechRecognition: boolean;
    mediaRecording: boolean;
    camera: boolean;
    vibration: boolean;
  };

  // 方法
  initializeDevice: () => Promise<{ deviceId: string; deviceInfo: any; capabilities: any }>;
  detectCapabilities: () => Promise<any>;
  registerDevice: (socket: any) => Promise<any>;
  updateDeviceName: (name: string) => void;
  resetDevice: () => void;
  getDeviceStats: () => any;
  user: null | { userId: string; nickname?: string; phone?: string; token: string };
  devices: Array<{ id: string; name: string; online: boolean }>;
  setUser: (user: DeviceStoreState['user']) => void;
  fetchDevices: () => Promise<void>;
}

export const useDeviceStore = create<DeviceStoreState>()(
  persist(
    (set, get) => ({
      // 设备信息
      deviceId: getLocalDeviceId(),
      deviceName: '',
      deviceType: 'mobile',
      isRegistered: getLocalDeviceId() ? true : false,
      registrationError: null,

      // 设备能力
      capabilities: {
        speechRecognition: false,
        mediaRecording: false,
        camera: false,
        vibration: false
      },

      user: null,
      devices: [],
      setUser: (user) => set({ user }),
      fetchDevices: async () => {
        const token = get().user?.token || localStorage.getItem('token')
        if (!token) return
        const res = await fetch('/api/devices', {
          headers: { 'Authorization': 'Bearer ' + token }
        })
        if (!res.ok) return
        const data = await res.json()
        set({ devices: data.devices || [] })
      },

      // 初始化设备（先确保 deviceId，再初始化本地信息）
      initializeDevice: async (socket?: any) => {
        try {
          let deviceId = getLocalDeviceId();
          console.log('deviceId from local storage', deviceId);
          
          // 检查是否需要重新注册
          if (deviceId) {
            const needsReRegister = await shouldReRegisterDevice();
            if (needsReRegister) {
              console.log('🔄 设备需要重新注册，清除旧ID');
              deviceId = null;
            }
          }
          
          // 如果没有 deviceId，且 socket 可用，则注册获取
          if (!deviceId && socket) {
            // 获取设备信息用于注册
            const deviceInfo = await getDeviceInfo();
            const deviceCapabilities = await get().detectCapabilities();
            
            deviceId = await registerDeviceAndSaveId(socket, {
              type: 'mobile',
              name: deviceInfo.name || 'Mobile Device', // 使用设备名称或默认名称
              capabilities: {
                canSendVoice: true,
                canReceiveText: false,
                canGenerateQR: false,
                canScanQR: true,
                speechRecognition: deviceCapabilities.speechRecognition,
                mediaRecording: deviceCapabilities.mediaRecording,
                camera: deviceCapabilities.camera,
                vibration: deviceCapabilities.vibration
              }
            });
          }
          
          // 此时 deviceId 必须存在
          if (!deviceId) {
            throw new Error('设备ID获取失败');
          }
          
          // 验证ID格式
          if (!validateDeviceId(deviceId)) {
            throw new Error('设备ID格式无效');
          }
          
          // 拿到 deviceId 后再初始化本地信息
          let deviceInfo = await getDeviceInfo();
          let capabilities = await get().detectCapabilities();
          set({
            deviceId: deviceId,
            deviceName: deviceInfo.name,
            deviceType: 'mobile',
            capabilities
          });
          return { deviceId, deviceInfo, capabilities };
        } catch (error) {
          console.error('设备初始化失败:', error);
          const errorMessage = error instanceof Error ? error.message : '设备初始化失败';
          set({ registrationError: errorMessage });
          throw error;
        }
      },

      // 检测设备能力
      detectCapabilities: async () => {
        const capabilities = {
          speechRecognition: false,
          mediaRecording: false,
          camera: false,
          vibration: false
        }

        try {
          // 检测语音识别支持
          capabilities.speechRecognition =
            'webkitSpeechRecognition' in window || 'SpeechRecognition' in window

          // 检测媒体录制支持
          capabilities.mediaRecording =
            navigator.mediaDevices &&
            typeof navigator.mediaDevices.getUserMedia === 'function'

          // 检测摄像头支持
          if (capabilities.mediaRecording) {
            try {
              const devices = await navigator.mediaDevices.enumerateDevices()
              capabilities.camera = devices.some(device => device.kind === 'videoinput')
            } catch (error) {
              console.warn('无法检测摄像头:', error)
            }
          }

          // 检测震动支持
          capabilities.vibration = 'vibrate' in navigator

        } catch (error) {
          console.error('检测设备能力失败:', error)
        }

        return capabilities
      },

      // 注册设备（负责注册并获取 deviceId，无id时自动注册并保存）
      registerDevice: (socket) => {
        return new Promise(async (resolve, reject) => {
          const { deviceName, deviceType, capabilities } = get();
          let deviceId = getLocalDeviceId();
          
          if (!deviceId && socket) {
            // 发送设备信息，让服务端生成ID
            const deviceInfo = {
              type: deviceType,
              name: deviceName || 'Mobile Device', // 确保设备名称不为空
              capabilities: {
                canSendVoice: true,
                canReceiveText: false,
                canGenerateQR: false,
                canScanQR: true,
                speechRecognition: capabilities.speechRecognition,
                mediaRecording: capabilities.mediaRecording,
                camera: capabilities.camera,
                vibration: capabilities.vibration
              }
              // 注意：不包含deviceId，让服务端生成
            };
            
            console.log('📤 发送设备注册请求（服务端生成ID）:', deviceInfo);
            
            const handleRegistered = (response: any) => {
              console.log('📥 收到设备注册响应:', response);
              if (response.success) {
                set({ isRegistered: true, registrationError: null, deviceId: response.deviceId });
                console.log('✅ 设备注册成功，服务端分配ID:', response.deviceId);
                resolve(response);
              } else {
                set({ isRegistered: false, registrationError: response.message || response.error });
                console.error('❌ 设备注册失败:', response.message || response.error);
                reject(new Error(response.message || response.error));
              }
              socket.off('device:registered', handleRegistered);
            };
            
            socket.on('device:registered', handleRegistered);
            socket.emit('device:register', deviceInfo);
            
            setTimeout(() => {
              socket.off('device:registered', handleRegistered);
              reject(new Error('设备注册超时'));
            }, 10000);
          } else if (deviceId) {
            // 已有设备ID，直接返回
            resolve({ success: true, deviceId });
          } else {
            reject(new Error('无法获取设备ID'));
          }
        });
      },

      // 更新设备名称
      updateDeviceName: (name) => {
        set({ deviceName: name })
      },

      // 重置设备（不清除deviceId）
      resetDevice: () => {
        set({
          // deviceId 不变
          deviceName: '',
          deviceType: 'mobile',
          isRegistered: false,
          registrationError: null,
          capabilities: {
            speechRecognition: false,
            mediaRecording: false,
            camera: false,
            vibration: false
          }
        })
      },

      // 恢复出厂设置（清除deviceId并重置所有状态）
      factoryResetDevice: async () => {
        const { clearDeviceId } = await import('../utils/device')
        clearDeviceId()
        set({
          deviceId: null,
          deviceName: '',
          deviceType: 'mobile',
          isRegistered: false,
          registrationError: null,
          capabilities: {
            speechRecognition: false,
            mediaRecording: false,
            camera: false,
            vibration: false
          }
        })
      },

      // 获取设备统计信息
      getDeviceStats: () => {
        const { deviceId, deviceName, deviceType, capabilities } = get()

        return {
          deviceId,
          deviceName,
          deviceType,
          capabilities,
          supportedFeatures: Object.keys(capabilities).filter(key => capabilities[key as keyof typeof capabilities])
        }
      }
    }),
    {
      name: 'smartinput-device',
      // partialize函数定义了哪些状态需要被持久化到本地存储
      partialize: (state) => ({
        deviceId: state.deviceId,
        deviceName: state.deviceName,
        deviceType: state.deviceType,
        capabilities: state.capabilities
        // 不再持久化pairedDevices、currentSession等配对相关状态
      })
    }
  )
)

// 在store定义外部，添加socket连接成功时自动刷新本地信息的监听
if (typeof window !== 'undefined') {
  window.addEventListener('socket-connected', async (e: any) => {
    try {
      const { getDeviceInfo, detectDeviceCapabilities } = await import('../utils/device');
      const deviceInfo = await getDeviceInfo();
      const capabilities = await detectDeviceCapabilities();
      useDeviceStore.setState({
        deviceName: deviceInfo.name,
        deviceType: 'mobile',
        capabilities,
        pairedDevices: [],
        currentSession: null
      });
      // 新增：重连后自动同步配对状态
      const { syncPairingStatus } = useDeviceStore.getState();
      const socket = e?.detail?.socket;
      if (socket && typeof syncPairingStatus === 'function') {
        await syncPairingStatus(socket);
        console.log('✅ 设备重连后已自动同步配对状态');
      }
    } catch (error) {
      console.error('自动刷新本地设备信息或同步配对状态失败:', error);
    }
  });
}
